#!/usr/bin/env python
###########################################################################
#  Copyright 2010 Jim Pulokas
#
#  This file is part of focusfun.
#  
#  focusfun is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#  
#  focusfun is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with focusfun.  If not, see <http://www.gnu.org/licenses/>.
###########################################################################

import time
import v4l2focuser

class Watcher(v4l2focuser.Focuser):
	'''
	Initialize it just like Focuser, then call either watch_changes or
	watch_stable to start an infinite loop.
	'''
	def watch_changes(self):
		'''
		Check focus value continuously.
		Report beginning and end of every focus change.
		'''
		## [time, focus, notsaved]
		f_old = [time.time(), None, False]
		while True:
			f_new = [time.time(), self.get(), True]
			if f_new[1] != f_old[1]:
				for f in (f_old, f_new):
					if f[2]:
						print f[0], f[1]
						f[2] = False
			f_old = f_new
	
	def watch_stable(self, dt):
		'''
		Check focus values continuously.
		Report only when values stays stable for dt or more seconds.
		'''
		t00 = t0 = time.time()
		f0 = self.get()
		stable = False
		while True:
			t1 = time.time()
			f1 = self.get()
	
			# if unchanged
			if f0 == f1:
				# if just got stable (not already stable):
				if not stable and t1-t0 > dt:
					stable = True
					print '%.2f,%d' % (t1-t00, f1)
			# changed
			else:
				t0 = t1
				f0 = f1
				stable = False

if __name__ == '__main__':
	import sys
	method = sys.argv[1]
	try:
		dev = sys.argv[2]
	except:
		dev = '/dev/video0'
	w = Watcher('/dev/video0')
	if method == 'changes':
		w.watch_changes()
	elif method == 'stable':
		w.watch_stable(0.01)
